package com.qunar.wan.web.controller;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.qunar.wan.common_api.model.Activity;
import com.qunar.wan.common_api.model.User;
import com.qunar.wan.common_api.model.enums.ActivityState;
import com.qunar.wan.common_api.model.enums.Role;
import com.qunar.wan.common_api.service.ActivityService;
import com.qunar.wan.common_api.service.LuceneSearchService;
import com.qunar.wan.common_api.service.UserService;
import com.qunar.wan.util.HTMLTagsUtil;
import com.qunar.wan.web.controller.common.AbstractController;
import com.qunar.wan.web.filter.AuthenticationController;
import org.apache.commons.lang3.StringUtils;
import com.qunar.wan.common_api.serializer.RowBounds;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.Future;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * User: meisiqi Date: 13-11-28 Time: 下午7:43
 */
@Controller
@RequestMapping("/admin")
public class AdminController extends AbstractController implements AuthenticationController {
    /**
     * 从个人中心到管理员系统
     */
    @Resource
    private UserService userService;
    @Resource
    private ActivityService activityService;
    @Resource
    private LuceneSearchService<Activity> luceneSearchService;

    @RequestMapping("/index")
    public String loginAdmin(ModelMap map) throws Exception {
        User user = checkNotNull(userService.currentLogonUser());
        map.put("user", user);
        return "/activity/adminIndex";
    }

    @RequestMapping(value = "/examine/list")
    public String examineActivitiesList(@RequestParam(defaultValue = "5", required = false) int pageSize,
            @RequestParam(defaultValue = "1", required = false) int page, ModelMap map) {
        RowBounds rowBounds = new RowBounds((page - 1) * pageSize, page * pageSize);
        int totalPage = (int) Math.ceil(((double) activityService.selectNotExaminedCount()) / pageSize);
        List<Activity> activities = activityService.selectNotExamined(rowBounds);
        List<Activity> escapedActivities = Lists.transform(activities,new Function<Activity, Activity>() {
            @Override
            public Activity apply(Activity input) {
                input.setPlace(HTMLTagsUtil.escapeHtml(input.getPlace(), null));
                input.setDescription(HTMLTagsUtil.escapeHtml(input.getDescription(), null));
                input.setTitle(HTMLTagsUtil.escapeHtml(input.getTitle(), null));
                input.setPoster(HTMLTagsUtil.escapeHtml(input.getPoster(), null));
                return input;
            }
        });
        map.put("activities", escapedActivities);
        map.put("totalPage", totalPage);
        map.put("curPage", page);
        return "/activity/examineActivity";
    }


    @RequestMapping(value = "/examine")
    @ResponseBody
    public Object examineActivity(@RequestParam int id, @RequestParam(defaultValue = "0") int state,
            @RequestParam(defaultValue = "未作评价", required = false) String comment, HttpServletRequest request)
            throws Exception {
        long start = System.currentTimeMillis();
        User admin = checkNotNull(userService.currentLogonUser());
        Activity activity = activityService.selectById(id);
        if (activity.getState() != ActivityState.CHECKING) {
            return errorJson(0, "该活动已经被审核", System.currentTimeMillis() - start);
        }
        activity.setState(ActivityState.codeOf(state));
        activity.setCheckComment(comment);
        activityService.examine(activity, admin);
        if (state == ActivityState.CHECK_SUCCESS.getCode()) {
            try {
                Future<Boolean> res =  luceneSearchService.addIndexDoc(activity);
                if (res.get()) {
                    logger.info("成功加入到索引文件(Title:{})", activity.getTitle());
                }
            } catch (Exception e) {
                logger.error("创建索引失败:{}", e);
            }
        }
        return dataJson("pass", System.currentTimeMillis() - start);
    }


    @Override
    public boolean isAuthenticated(String pathInfo, ServletRequest req) {
        HttpServletRequest request = (HttpServletRequest) req;
        User user = userService.currentLogonUser();
        if (user != null && (user.getRole() == Role.MANAGER || user.getRole() == Role.SUPERMANAGER)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isCheckRequired(ServletRequest req) {
        return true;
    }
}
